
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from rest_framework import status
from django_redis import get_redis_connection

import logging
from django.conf import settings
from course.models import Course

log = logging.getLogger('django')
# Create your views here.


class CartAPIView(ViewSet):
	permission_classes = [IsAuthenticated, ]

	def add(self, request):
		course_id = request.data.get('course_id')
		user_id = request.user.id
		expire_time = 0
		try:
			Course.objects.get(is_show=True, is_deleted=False, id=course_id)
		except:
			return Response({'error': '参数有误，该课程不存在'}, status=status.HTTP_400_BAD_REQUEST)
		conn = get_redis_connection('cart')
		try:
			cart_list = conn.smembers(f'selected_{user_id}')
			if course_id.encode() in cart_list:
				return Response({'message': '该课程已加入购物车'})
		except:
			return Response({'error': '参数有误！购物车添加商品失败！'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
		try:
			pipe = conn.pipeline()
			pipe.multi()
			pipe.hset(f'cart_{user_id}', course_id, expire_time)
			pipe.sadd(f'selected_{user_id}', course_id)
			pipe.execute()
		except:
			log.error('购物车数据库储存出错')
			return Response({'error': '参数有误！购物车添加商品失败！'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
		return Response({"message": "购物车商品添加成功！"})

	def list(self, request):
		user_id = request.user.id
		conn = get_redis_connection('cart')
		cart_byte_dict = conn.hgetall(f'cart_{user_id}')
		selected_byte_list = conn.smembers(f'selected_{user_id}')
		date = []
		for course_id_byte, expire in cart_byte_dict.items():
			course_id = course_id_byte.decode()
			expire = expire.decode()
			try:
				course = Course.objects.get(is_show=True, is_deleted=False, id=course_id)
				expire_time = int(conn.hget(f'cart_{user_id}', course_id).decode())
			except Course.DoesNotExist:
				continue
			date.append({
				'selected': course_id_byte in selected_byte_list,
				'name': course.name,
				'id': course_id,
				'expire': expire,
				'price': course.price,
				'real_price': course.real_price(expire_time),
				'course_img': course.course_img.url.replace('/media', f'{settings.SERVER_HOST}/media'),
				'expire_list': course.expire_list,
			})
		return Response(date)

	def changeSelected(self, request):
		user_id = request.user.id
		selected = request.data.get('selected')
		course_id = request.data.get('course_id')
		try:
			course = Course.objects.get(is_show=True,is_deleted=False,id=course_id)
		except:
			return Response({'error': '该课程不存在'}, status=status.HTTP_400_BAD_REQUEST)
		conn = get_redis_connection('cart')
		if selected:
			conn.sadd(f'selected_{user_id}', course_id)
			return Response({'msg': '勾选成功'})
		conn.srem(f'selected_{user_id}', course_id)
		return Response({'msg': '取消勾选成功'})

	def change_expire(self, request):
		user_id = request.user.id
		expire_time = request.data.get('expire_time')
		course_id = request.data.get('course_id')
		conn = get_redis_connection('cart')
		if type(expire_time) == int:
			try:
				course = Course.objects.get(is_show=True, is_deleted=False, id=course_id)
				conn.hset(f'cart_{user_id}', course_id, expire_time)
				real_price = course.real_price(expire_time)
			except:
				return Response({'error': '该课程不存在'}, status=400)
			return Response({'msg': 'success', 'real_price': real_price})

		return Response({'error': '非法请求'}, status=400)


class CartDelAPIView(ViewSet):
	permission_classes = [IsAuthenticated, ]

	def del_cart(self, request):
		user_id = request.user.id
		course_id = request.data.get("course_id")
		try:
			Course.objects.get(is_show=True, is_deleted=False, id=course_id)
		except Course.DoesNotExist:
			return Response({"message":"参数有误！当前商品课程不存在！"}, status=status.HTTP_400_BAD_REQUEST)
		redis_conn = get_redis_connection("cart")
		pipe = redis_conn.pipeline()
		pipe.multi()
		pipe.hdel('cart_%s' % user_id, course_id)
		pipe.srem("selected_%s" % user_id, course_id)
		pipe.execute()
		return Response({"message": "删除商品成功！"})